package me.magicall.web.simple.spring.controllers;

import me.magicall.web.simple.spring.util.UrlPatternRule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(method = RequestMethod.GET, //
value = { UrlPatternRule.SINGULAR_MODEL_NAME,//
})
@Controller("editController")
public class ToEditController {

	@Autowired
	private ApplicationContext context;
	@Autowired
	private GetOneController oneController;

	@RequestMapping({ UrlPatternRule.ID + "/edit",//
			"/edit" + UrlPatternRule.ID //
	})
	public String edit(final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName,//
			@PathVariable("id") final long id) {
		oneController.one(modelMap, modelName, id);

		final String modelName1 = StringUtils.capitalize(modelName);
		if (context.getResource("/WEB-INF/views/edit" + modelName1 + ".jsp").exists()) {
			return "/edit" + modelName1;
		}
		return "edit";
	}

	@RequestMapping({ "/{op:edit}", "/edit" })
	public String edit(final ModelMap modelMap, @PathVariable("modelName") final String modelName) {
		return edit(modelMap, modelName, 0);
	}
}
